package com.etoak.util;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.lang3.StringUtils;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *  Java Bean校验工具类
 */
public class ValidatorUtil {

    /** 校验器 */
    private static Validator validator;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    public static void validate(Object object){
        Set<ConstraintViolation<Object>> violations = validator.validate(object);
        if(CollectionUtil.isNotEmpty(violations)){
            //{"name必填","email必填"}
            List<String> messageList = violations.stream().map(v ->{
                String field = v.getPropertyPath().toString();
                String message = v.getMessage();
                return StringUtils.join(field,message);
            }).collect(Collectors.toList());

            throw new RuntimeException(StringUtils.join(messageList,";"));
        }
    }
}
